package com.ldg.user.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ldg.user.config.UserInfo;
import com.ldg.user.dao.TbUserMapper;
import com.ldg.user.entity.TbUser;
import com.ldg.user.service.TbUserService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
//import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
//    private RabbitTemplate rabbitTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserInfo userInfo;
    /**
     * 1. 使用手机发送验证胎囊
     * @param phone
     */
    @Override
    public void sendCode(String phone) {
        //生成验证码并放到redis中
        //生成四位验证码
        String code = RandomUtil.randomNumbers(4);
        System.out.println("code = " + code);
        //放到redis中
        redisTemplate.opsForValue().set(phone,code,10, TimeUnit.HOURS);

        //发送阿里云需要的信息，由监听方接收信息，收到信息后再给阿里云发送信息
        Map<String,String> map = new HashMap<>();
        map.put("code",code);
        userInfo.setTemplateParam(JSON.toJSONString(map));
        userInfo.setPhone(phone);
        rocketMQTemplate.convertAndSend("codeMsg",JSON.toJSONString(userInfo));
//        rabbitTemplate.convertAndSend("codeMsg",JSON.toJSONString(userInfo));
    }

    /**
     * 2. 验证码是否存在
     * @param phone
     * @param validCode
     * @return
     */
	@Override
	public boolean isExistCode(String phone, String validCode) {
	    //从redis中取得验证码
        String code = redisTemplate.opsForValue().get(phone);
        //与传入的验证码比较
        return validCode.equals(code);
	}
}

